let App = getApp();

Page({
  data: {
    list: [],
    default_id: null,
  },

user_id :10001,
  onLoad: function(options) {
    // 当前页面参数
    this.data.options = options;
  },

  onShow: function() {
    // 获取收货地址列表
    this.getAddressList();
  },

  /**
   * 获取收货地址列表
   */
  getAddressList: function() {
    let _this = this;
    let user_id = 10001;
    let data= {
    list: [],
    default_id: null,
  }

    App._get('address/lists', {}, function(result) {
     data =  _this.initData(result.data);
      _this.setData(data);
          console.log("k1",_this.data.list[0].address_id)
          //console.log("k2",_this.data.list[1].address_id)
          console.log("第"+"次",_this.data.list[0].address_id)
    });
  },

initData(datas){
  console.log("数据",datas);
   let _this = this;
   let datap= {
    list: [],
    default_id: null,
  }
  datap.default_id = datas.default_id;


  for(let i in datas.userAddressList){
       let dataArr={
     name:"",
     phone:"",
     province:"",
     city:"",
     region:"",
     detail:"",
     address_id:"",
   };

    dataArr.name = datas.userAddressList[i].userAddress.name;
    dataArr.phone = datas.userAddressList[i].userAddress.phone;
    dataArr.detail = datas.userAddressList[i].userAddress.detail;
    dataArr.address_id = datas.userAddressList[i].userAddress.id;

    let arr = datas.userAddressList[i].region.merger_name.split(",");

    dataArr.province = arr[1];
    if(arr.length>=3)
      dataArr.city = arr[2];
    else 
      dataArr.city = " ";
    if(arr.length>=4)
      dataArr.region = arr[3];
    else 
        dataArr.region = " ";
    datap.list[i]=dataArr;
   }
    return datap;
},


  /**
   * 添加新地址
   */
  createAddress: function() {
    wx.navigateTo({
      url: './create'
    });
  },

  /**
   * 编辑地址
   */
  editAddress: function(e) {
    wx.navigateTo({
      url: "./detail?address_id=" + e.currentTarget.dataset.id
    });
  },

  /**
   * 移除收货地址
   */
  removeAddress: function(e) {
    let _this = this,
      address_id = e.currentTarget.dataset.id;
    wx.showModal({
      title: "提示",
      content: "您确定要移除当前收货地址吗?",
      success: function(o) {
        o.confirm && App._post_form('address/delete', {
          address_id:address_id,
          user_id:10001
        }, function(result) {
          _this.getAddressList();
        });
      }
    });
  },

  /**
   * 设置为默认地址
   */
  setDefault: function(e) {
    let _this = this,
      address_id = e.detail.value;
    _this.setData({
      default_id: parseInt(address_id)
    });
    App._post_form('address/setDefault/'+address_id, {
        user_id:10001
    }, function(result) {
      _this.data.options.from === 'flow' && wx.navigateBack();
    });
    return false;
  },

});